package com.summer.mall.controller.admin;

import com.summer.mall.entity.CustomService;
import com.summer.mall.entity.Result;
import com.summer.mall.service.impl.CustomServiceServiceImpl;
import com.summer.mall.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RestController
@RequestMapping("/cs")
public class CustomServiceController {
    @Autowired
    CustomServiceServiceImpl customServiceService;
    @Autowired
    HttpSession session;

    @PostMapping("/login")
    public Result login(@Valid CustomService customService, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.failure(bindingResult.getFieldError().getDefaultMessage());
        }
        CustomService temp = customServiceService.selectCustomServiceByName(customService.getCs_name());
        if (temp.getCs_password().equals(customService.getCs_password())) {
            temp.setSessionId(session.getId());
            session.setAttribute("customService", temp);
            return ResultUtil.success();
        }
        return ResultUtil.failure("name or password wrong.");
    }

    @GetMapping("/logout")
    public Result logout() {
        session.removeAttribute("customService");
        return ResultUtil.success();
    }
}
